package com.sengled.cloud.biz.union.mgt.service.sys.impl;

import com.sengled.cloud.biz.union.mgt.model.request.SaveUserAccountRequest;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.sengled.cloud.biz.union.mgt.common.PageUtil;
import com.sengled.cloud.biz.union.mgt.common.util.Md5Util;
import com.sengled.cloud.biz.union.mgt.dao.sys.ShopAccountDao;
import com.sengled.cloud.biz.union.mgt.dao.sys.ShopDao;
import com.sengled.cloud.biz.union.mgt.dao.sys.UserAccountDao;
import com.sengled.cloud.biz.union.mgt.dao.sys.UserDao;
import com.sengled.cloud.biz.union.mgt.model.po.Shop;
import com.sengled.cloud.biz.union.mgt.model.po.UserAccountDetail;
import com.sengled.cloud.biz.union.mgt.model.request.SaveShopRequest;
import com.sengled.cloud.biz.union.mgt.model.response.ResponseMessage;
import com.sengled.cloud.biz.union.mgt.model.vo.QueryData;
import com.sengled.cloud.biz.union.mgt.model.vo.SelectBoxDataVo;
import com.sengled.cloud.biz.union.mgt.model.vo.ShopDetailVo;
import com.sengled.cloud.biz.union.mgt.model.vo.ShopEditVo;
import com.sengled.cloud.biz.union.mgt.model.vo.ShopQueryParamsBean;
import com.sengled.cloud.biz.union.mgt.model.vo.ShopVo;
import com.sengled.cloud.biz.union.mgt.service.sys.IShopService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by FMC on 2017/10/27.
 */
@Service("shopService")
@Transactional(value="txManager",rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
public class ShopService implements IShopService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    ShopDao shopDao;
    
    @Autowired
    UserDao userDao;

    @Autowired
    UserAccountDao userAccountDao;
    
    @Override
    public ResponseMessage saveOrUpdate(SaveShopRequest saveShopRequest,Long operatorId) {
        ResponseMessage rm = new ResponseMessage<>();
        if (null == saveShopRequest) {
            rm.buildParamErrorMessage();
            return rm;
        }
        if(StringUtils.isEmpty(saveShopRequest.getShopCode())||StringUtils.isEmpty(saveShopRequest.getShopName())||StringUtils.isEmpty(saveShopRequest.getShopTel())||saveShopRequest.getShopNature()==null||StringUtils.isEmpty(saveShopRequest.getCountryCode())||StringUtils.isEmpty(saveShopRequest.getProvinceCode())||StringUtils.isEmpty(saveShopRequest.getCityCode())){
        	rm.buildParamErrorMessage();
            return rm;
        }
     
        try {
            Shop shop = new Shop();
            BeanUtils.copyProperties(shop, saveShopRequest);
            if(StringUtils.isNotEmpty(saveShopRequest.getEstablishDateStr())){
            	shop.setEstablishDate(strToDate(saveShopRequest.getEstablishDateStr()));
            	//shop.setEstablishDate(strToDate(saveShopRequest.getEstablishDateStr()));
                //shop.setEstablishDate(new Date(saveShopRequest.getEstablishDateStr()));
            }
            int ret;
            int ret1;
            
            int shopCodeNum = shopDao.getShopCountByShopCode(saveShopRequest.getShopCode(),getCompanyId(operatorId));
            //int accountNum = shopDao.getShopCountByAccountName(saveShopRequest.getShopName());
            
            if (null != shop.getId()) {
            	ShopDetailVo m = shopDao.selectByPrimaryKey(shop.getId());
            	if(m==null){
            		  rm.buildParamErrorMessage();
                      return rm;
            	}
            	
            	if(!m.getShopCode().equals(saveShopRequest.getShopCode())&&shopCodeNum>0){
            		rm.buildShopCodeRepeatMessage();
                 	return rm;
            	}
                //shop.setCreateDate(new Date());
                shop.setModifyDate(new Date());
                shop.setSealMark(0);
                shop.setCompanyId(getCompanyId(operatorId));
                shop.setOperatorId(operatorId);
                ret = shopDao.updateByPrimaryKey(shop);
                ret1 = shopDao.updateShopAccount(shop);
            } else {
            	
            	if(shopCodeNum>0){
            		rm.buildShopCodeRepeatMessage();
                 	return rm;
                 }
            	
            	shop.setCreateDate(new Date());
            	shop.setSealMark(0);
            	shop.setCompanyId(getCompanyId(operatorId));
                shop.setOperatorId(operatorId);
                ret = shopDao.insert(shop);
                //System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>insert shop ret:");
                //System.out.println(">>>>>>>>>>>>>>>>>>>>>>>trasaction test>>>>>>>>>>>>>>>>>>>>"+1/0);
                shop.setId(shop.getId());
                shop.setStr001(Md5Util.md5("888888"));
                ret1 = shopDao.insertShopAccount(shop);
                SaveUserAccountRequest saveUserAccountRequest = new SaveUserAccountRequest();
                saveUserAccountRequest.setOperatorId(operatorId);
                saveUserAccountRequest.setId(operatorId);
                List<Long> shopAccountIds = new ArrayList<Long>(1);
                shopAccountIds.add(shop.getId());
                saveUserAccountRequest.setShopAccountIds(shopAccountIds);
                userAccountDao.insertAccountShop(saveUserAccountRequest);
            }
            if (0 == ret) {
                rm.buildExecuteFailMessage();
            }
            if (0 == ret1) {
                rm.buildExecuteFailMessage();
            }
            return rm;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.buildSystemErrorMessage();
            return rm;
        }
    }

    @Override
    public ResponseMessage delete(Long id) {
        ResponseMessage rm = new ResponseMessage<>();
        if (null == id || id.intValue() < 0) {
            rm.buildParamErrorMessage();
            return rm;
        }
        try {
            Calendar c = Calendar.getInstance();
           // Long shopAccountId = shopDao.getShopAccountIdByShopId(id);
            
            shopDao.deleteShopAccountModule(id);
            shopDao.deleteUserAcctShopAcct(id);
            shopDao.deleteShopAccount(id);
            shopDao.deleteByPrimaryKey(id);
            
//            int ret = shopDao.deleteByPrimaryKey(id);
//            int ret1 = shopDao.deleteShopAccount(id);
//            if (0 == ret) {
//                rm.buildExecuteFailMessage();
//            }
//            if (0 == ret1) {
//                rm.buildExecuteFailMessage();
//            }
       
            return rm;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.buildSystemErrorMessage();
            return rm;
        }
    }

    @Override
    public ResponseMessage<ShopDetailVo> getShopDetailById(Long id) {
        ResponseMessage rm = new ResponseMessage<>();
        if (null == id || id.intValue() < 0) {
            rm.buildParamErrorMessage();
            return rm;
        }
        try {
        	ShopDetailVo m = shopDao.selectByPrimaryKey(id);
            if (null != m) {
                rm.setData(m);
            }
            return rm;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            rm.buildSystemErrorMessage();
            return rm;
        }
    }
    
    
    @Override
    public ResponseMessage<ShopEditVo> getShopEditDataById(Long id) {
        ResponseMessage rm = new ResponseMessage<>();
        if (null == id || id.intValue() < 0) {
            rm.buildParamErrorMessage();
            return rm;
        }
        try {
        	ShopEditVo m = shopDao.getShopEditData(id);
            if (null != m) {
                rm.setData(m);
            }
            return rm;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            rm.buildSystemErrorMessage();
            return rm;
        }
    }

    @Override
    public ResponseMessage<List<ShopVo>> listShopsByPage(ShopQueryParamsBean q) {
    	
    	
    	QueryData<List<ShopVo>> queryData = new QueryData();
    	
        ResponseMessage rm = new ResponseMessage<>();
        if (null == q) {
            rm.buildParamErrorMessage();
            return rm;
        }
        try {
        	boolean isSuperManager = isSuperManager(q.getUserId());
        	q.setSuperMgr(isSuperManager);
            List<ShopVo> ms = shopDao.listMessageByPage(q);
            Integer totalRecords = shopDao.queryShopTotalRecords(q);
            if (null != ms && !ms.isEmpty()) {
            	queryData.setData(ms);
                
            }
            
            queryData.setTotalCount(totalRecords);
            
            //int totalPages = totalRecords%q.getPageSize()==0?totalRecords/q.getPageSize():totalRecords/totalRecords+1;
            if(totalRecords>0){
				PageUtil pageUtil = new PageUtil(q.getPageNo(),
						q.getPageSize(), totalRecords);
				queryData.setTotalPage(pageUtil.getPageCount());
				queryData.setBeginIndex(pageUtil.getStartIndex());
				queryData.setEndIndex(pageUtil.getEndIndex());
            }else{
            	queryData.setTotalPage(1);
                queryData.setBeginIndex(0);
                queryData.setEndIndex(0);
            }
            queryData.setPageNo(q.getPageNo());
            queryData.setPageSize(q.getPageSize());
            rm.setData(queryData);
            
            return rm;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            rm.buildSystemErrorMessage();
            return rm;
        }
    }
//
//    @Override
//    public ResponseMessage updatePassStatus(Long id) {
//        ResponseMessage rm = new ResponseMessage<>();
//        if (null == id || id.intValue() < 0) {
//            rm.buildParamErrorMessage();
//            return rm;
//        }
//        try {
//            Calendar c = Calendar.getInstance();
//            int ret = messageDao.updatePassStatus(c.getTime(), id);
//            if (0 == ret) {
//                rm.buildExecuteFailMessage();
//            }
//            return rm;
//        } catch (Exception e) {
//            logger.error(e.getMessage(), e);
//            rm.buildSystemErrorMessage();
//            return rm;
//        }
//    }
//
//    @Override
//    public Message getById(Long id) {
//        if (null == id || id.intValue() < 0) {
//            return null;
//        }
//        try {
//            Message m = messageDao.getMessageById(id);
//            if (null != m) {
//                return m;
//            }
//            return null;
//        } catch (Exception e) {
//            logger.error(e.getMessage(), e);
//            return null;
//        }
//    }
    
    public static Date strToDate(String str) {
    	  
    	   SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    	   Date date = null;
    	   try {
    	    date = format.parse(str);
    	   } catch (ParseException e) {
    	    e.printStackTrace();
    	   }
    	   return date;
    	}
    
//    @Override
//    public ResponseMessage<List<SelectBoxDataVo>> getShopSelectData(){
//    	 ResponseMessage rm = new ResponseMessage<>();
//         
//         try {
//        	 List<SelectBoxDataVo> m = shopDao.getShopSelectData();
//        	 SelectBoxDataVo selectBoxDataVo = new SelectBoxDataVo();
//        	 //map.put(0L, "全部");
//        	 selectBoxDataVo.setId(0L);
//        	 selectBoxDataVo.setName("全部");
//        	        	 
//             if (null != m) {
//            	 m.set(0, selectBoxDataVo);                 
//             }else{
//            	 m = new ArrayList<SelectBoxDataVo>();
//            	 m.set(0, selectBoxDataVo);
//             }
//             rm.setData(m);
//             return rm;
//         } catch (Exception e) {
//             logger.error(e.getMessage(), e);
//             rm.buildSystemErrorMessage();
//             return rm;
//         }
//    }
    @Override
    public Long getCompanyId(Long userId){
    	//Long userId = 1L;
    	Long companyId = userDao.queryUserCompanyId(userId);
    	return companyId;

    }
    

    public boolean isSuperManager(Long customerId) {
        
        try {
            int ret = userAccountDao.getSuperManager(customerId);
            if (0 == ret) {
               return false;
            }
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }
}
